from flask import Flask, render_template, request, redirect, url_for, session, jsonify, flash
from datetime import datetime, timedelta
import mysql.connector
import os

app = Flask(__name__)
app.secret_key = 'your_secret_key'
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'docx'}

# MySQL数据库配置
try:
    db = mysql.connector.connect(
        host="152.136.49.229",
        user="yuyu",
        password="123456",
        database="userinfo",
        charset='utf8mb4'
    )
    print("数据库连接成功")
except mysql.connector.Error as err:
    print("数据库连接失败: {err}")

# 登录
@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        password = request.form['password']

        cursor = db.cursor(dictionary=True)
        cursor.execute("SELECT * FROM users WHERE username=%s AND password=%s AND role=%s", (username, password, user_type))
        user = cursor.fetchone()

        if user:
            session['username'] = username
            session['user_type'] = user_type
            if user_type == 'student':
                return redirect(url_for('student_dashboard', username=username))
            elif user_type == 'teacher':
                return redirect(url_for('teacher_dashboard', username=username))
            elif user_type == 'parent':
                return redirect(url_for('parent_dashboard', username=username))
        else:
            flash('登录失败，用户名或密码错误！', 'danger')
            return redirect(url_for('login'))

    return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        user_id = request.form['id']  # 确保数据库中有对应的id字段
        password = request.form['password']

        print(f"尝试注册用户: {username}，类型: {user_type}")

        cursor = db.cursor(dictionary=True)
        cursor.execute("SELECT * FROM users WHERE username=%s", (username,))
        existing_user = cursor.fetchone()

        if existing_user:
            print("用户名已存在")
            flash('用户名已存在，请选择其他用户名。', 'danger')
            return redirect(url_for('register'))

        try:
            # 尝试插入用户数据
            cursor.execute("INSERT INTO users (username, password, id, role) VALUES (%s, %s, %s, %s)",
                           (username, password, user_id, user_type))
            db.commit()
            print("用户注册成功")
            flash('注册成功！', 'success')
            return redirect(url_for('register_success'))

        except mysql.connector.Error as err:
            print("插入用户数据失败: {err}")
            flash('注册失败: {err}', 'danger')
            return redirect(url_for('register'))

    return render_template('register.html')

@app.route('/register_success')
def register_success():
    return render_template('register_success.html')

@app.route('/forgot_password', methods=['GET', 'POST'])
def forgot_password():
    if request.method == 'POST':
        user_type = request.form['user_type']
        username = request.form['username']
        new_password = request.form['new_password']

        cursor = db.cursor(dictionary=True)
        cursor.execute("SELECT * FROM users WHERE username=%s AND role=%s", (username, user_type))
        user = cursor.fetchone()

        if user:
            cursor.execute("UPDATE users SET password=%s WHERE username=%s AND role=%s",
                           (new_password, username, user_type))
            db.commit()
            flash('密码重置成功！', 'success')
            return redirect(url_for('password_reset_success'))
        else:
            flash('用户名不存在。', 'danger')
            return redirect(url_for('forgot_password'))

    return render_template('forgot_password.html')

@app.route('/password_reset_success')
def password_reset_success():
    return render_template('password_reset_success.html')

# 学生页面
@app.route('/student_dashboard/<username>', methods=['GET', 'POST'])
def student_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    cursor = db.cursor(dictionary=True)

    if request.method == 'POST':
        class_name = request.form['class_name']

        # 更新学生的班级
        cursor.execute("UPDATE users SET class_name=%s WHERE username=%s AND role='student'", (class_name, username))
        db.commit()

        # 检查学生是否已经加入班级
        cursor.execute("SELECT * FROM student_classes WHERE class_name=%s AND student_id=(SELECT id FROM users WHERE username=%s)", (class_name, username))
        class_data = cursor.fetchone()

        # 如果未加入班级，则添加
        if not class_data:
            cursor.execute("INSERT INTO student_classes (student_id, class_name) VALUES ((SELECT id FROM users WHERE username=%s), %s)", (username, class_name))
            db.commit()

        flash(f'成功加入班级 {class_name}！', 'success')
        return redirect(url_for('student_class', username=username, class_name=class_name))

    cursor.execute("SELECT class_name FROM users WHERE username=%s AND role='student'", (username,))
    student_class = cursor.fetchone()
    student_class_name = student_class['class_name'] if student_class else None

    return render_template('student_dashboard.html', username=username, class_name=student_class_name)

# 学生选择加入考试页面（无 exam 表，功能可修改）
@app.route('/student_class/<username>/<class_name>', methods=['GET', 'POST'])
def student_class(username, class_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    cursor = db.cursor(dictionary=True)

    if request.method == 'POST':
        exam_name = request.form.get('exam_name')
        # 由于不使用 exams 表，假设 exam_name 是某种标识符，可以直接跳转到考试页面
        session['exam_name'] = exam_name
        session['class_name'] = class_name
        return redirect(url_for('exam_page', class_name=class_name, exam_name=exam_name))

    # 如果有其他数据源用来获取考试列表，可以在这里添加
    exam_list = []  # 空的考试列表，仅作展示

    return render_template('student_class.html', username=username, class_name=class_name, exams=exam_list)

# 考试页面（不依赖 exam 表）
@app.route('/exam/<class_name>/<exam_name>', methods=['GET', 'POST'])
def exam_page(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    remaining_seconds = 3600  # 假设剩余考试时间为 1 小时
    return render_template('exam.html', remaining_time=remaining_seconds, class_name=class_name, exam_name=exam_name)

# 新增的考试完成页面
@app.route('/exam_finished/<class_name>/<exam_name>', methods=['GET'])
def exam_finished(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    return render_template('exam_finished.html', class_name=class_name, exam_name=exam_name, username=session['username'])

@app.route('/submit_exam/<class_name>/<exam_name>', methods=['POST'])
def submit_exam(class_name, exam_name):
    if 'user_type' not in session or session['user_type'] != 'student':
        return redirect(url_for('login'))

    try:
        exam_start_time_str = session.get('exam_start_time')
        if not exam_start_time_str:
            raise ValueError("考试开始时间未找到")

        exam_start_time = datetime.strptime(exam_start_time_str, '%Y-%m-%d %H:%M:%S.%f')
        elapsed_time = datetime.now() - exam_start_time
        elapsed_seconds = int(elapsed_time.total_seconds())

        session.pop('exam', None)
        session.pop('exam_start_time', None)

        return render_template('exam_finished.html', class_name=class_name, exam_name=exam_name,
                               elapsed_seconds=elapsed_seconds, username=session['username'])
    except Exception as e:
        return render_template('exam_finished.html', class_name=class_name, exam_name=exam_name, error=str(e),
                               username=session['username'])

# 老师页面
@app.route('/teacher_dashboard/<username>', methods=['GET', 'POST'])
def teacher_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    if request.method == 'POST':
        if 'add_exam' in request.form:
            return redirect(url_for('create_exam', username=username))

    return render_template('teacher_dashboard.html', username=username)

# 这是你需要添加的 create_exam 路由
@app.route('/create_exam/<username>', methods=['GET', 'POST'])
def create_exam(username):
    # 在这里处理创建考试的逻辑
    if request.method == 'POST':
     pass
    return render_template('create_exam.html', username=username)


@app.route('/manage_class/<username>', methods=['GET', 'POST'])
def manage_class(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    if request.method == 'POST':
        class_name = request.form.get('class_name', '')
        if not class_name:
            flash('班级名称不能为空', 'danger')
            return redirect(url_for('manage_class', username=username))

        return redirect(url_for('class_management', class_name=class_name))

    return render_template('teacher_dashboard.html', username=username)


@app.route('/class_management/<class_name>', methods=['GET'])
def class_management(class_name):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    cursor = db.cursor(dictionary=True)
    cursor.execute("SELECT username FROM users WHERE class_name=%s AND role='student'", (class_name,))
    students = cursor.fetchall()

    return render_template('class_management.html', class_name=class_name, students=students)

# 设置考试时间页面（可视情况移除）
@app.route('/set_exam_time/<username>', methods=['GET', 'POST'])
def set_exam_time(username):
    if 'user_type' not in session or session['user_type'] != 'teacher':
        return redirect(url_for('login'))

    # 由于不使用 exams 表，可直接返回管理页面或其他逻辑
    if request.method == 'POST':
        flash('考试时间设置功能暂时不可用。', 'warning')
        return redirect(url_for('teacher_dashboard', username=username))

    return redirect(url_for('teacher_dashboard', username=username))

# 家长页面
@app.route('/parent_dashboard/<username>')
def parent_dashboard(username):
    if 'user_type' not in session or session['user_type'] != 'parent':
        return redirect(url_for('login'))

    return render_template('parent_dashboard.html', username=username)

# 记录作弊行为
@app.route('/record_cheating', methods=['POST'])
def record_cheating():
    if 'username' in session:
        username = session['username']
        cursor = db.cursor(dictionary=True)
        cursor.execute("SELECT cheating_count FROM users WHERE username=%s", (username,))
        cheating_count = cursor.fetchone().get('cheating_count', 0)

        cheating_count += 1
        cursor.execute("UPDATE users SET cheating_count=%s WHERE username=%s", (cheating_count, username))
        db.commit()

        max_cheat_attempts = 2
        if cheating_count > max_cheat_attempts:
            return jsonify({'terminate': True})
        return jsonify({'terminate': False})
    return jsonify({'error': 'User not logged in'}), 401

# 终止考试
@app.route('/terminate_exam')
def terminate_exam():
    session.pop('exam', None)
    flash("由于检测到多次作弊行为，您的考试已被终止。", 'danger')
    return redirect(url_for('login'))

def get_db_connection():
    conn = mysql.connector.connect(
        host='152.136.49.229',
        user='yuyu',
        password='123456',
        database='yuyude',
        charset='utf8mb4'
    )
    return conn


@app.route('/generate_exam', methods=['GET', 'POST'])
def generate_exam():
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    if request.method == 'POST':
        # 选择题库处理
        xuanze_count = int(request.form['xuanze_count'])
        xuanze_randomize = 'xuanze_randomize' in request.form
        xuanze_selected_ids = request.form.getlist('xuanze_question_ids')

        tiankong_count = int(request.form['tiankong_count'])
        tiankong_randomize = 'tiankong_randomize' in request.form
        tiankong_selected_ids = request.form.getlist('tiankong_question_ids')

        zhuguan_count = int(request.form['zhuguan_count'])
        zhuguan_randomize = 'zhuguan_randomize' in request.form
        zhuguan_selected_ids = request.form.getlist('zhuguan_question_ids')

        # 创建试卷
        title = "My New Exam"
        description = "This is a dynamically generated exam."
        cursor.execute('INSERT INTO papers (title, description) VALUES (%s, %s)', (title, description))
        paper_id = cursor.lastrowid

        # 处理选择题库
        if xuanze_randomize:
            cursor.execute('SELECT * FROM questionsxuanze ORDER BY RAND() LIMIT %s', (xuanze_count,))
        else:
            if xuanze_selected_ids:
                cursor.execute('SELECT * FROM questionsxuanze WHERE id IN ({",".join(xuanze_selected_ids)})')
        xuanze_questions = cursor.fetchall()

        # 处理填空题库
        if tiankong_randomize:
            cursor.execute('SELECT * FROM questionstiankong ORDER BY RAND() LIMIT %s', (tiankong_count,))
        else:
            if tiankong_selected_ids:
                cursor.execute('SELECT * FROM questionstiankong WHERE id IN ({",".join(tiankong_selected_ids)})')
        tiankong_questions = cursor.fetchall()

        # 处理主观题库
        if zhuguan_randomize:
            cursor.execute('SELECT * FROM questionszhuguan ORDER BY RAND() LIMIT %s', (zhuguan_count,))
        else:
            if zhuguan_selected_ids:
                cursor.execute('SELECT * FROM questionszhuguan WHERE id IN ({",".join(zhuguan_selected_ids)})')
        zhuguan_questions = cursor.fetchall()

        # 保存所有题目到试卷
        all_questions = xuanze_questions + tiankong_questions + zhuguan_questions

        for question in all_questions:
            cursor.execute('''
                INSERT INTO examquestions (paper_id, question_text, option_a, option_b, option_c, option_d, correct_answer, question_type)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
            ''', (
                paper_id,
                question['question_text'],
                question.get('option_a'),
                question.get('option_b'),
                question.get('option_c'),
                question.get('option_d'),
                #question['correct_answer'],
                question.get('correct_answer'),
                question['question_type']  # 添加 question_type 列
               # question.get('question_type')
            ))

        conn.commit()
        cursor.close()
        conn.close()

        return redirect(url_for('exam_list', paper_id=paper_id))

    # 如果是 GET 请求，显示所有可选题目
    cursor.execute('SELECT * FROM questionsxuanze')
    xuanze_questions = cursor.fetchall()

    cursor.execute('SELECT * FROM questionstiankong')
    tiankong_questions = cursor.fetchall()

    cursor.execute('SELECT * FROM questionszhuguan')
    zhuguan_questions = cursor.fetchall()

    cursor.close()
    conn.close()

    return render_template('generate_exam.html',
                           xuanze_questions=xuanze_questions,
                           tiankong_questions=tiankong_questions,
                           zhuguan_questions=zhuguan_questions)


@app.route('/exam_list/<int:paper_id>')
def exam_list(paper_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    # 获取指定试卷的所有题目
    cursor.execute('SELECT * FROM examquestions WHERE paper_id = %s', (paper_id,))
    questions = cursor.fetchall()

    cursor.close()
    conn.close()

    return render_template('exam_list.html', questions=questions, exam_id=paper_id)

@app.route('/edit_exam_question/<int:question_id>', methods=['GET', 'POST'])
def edit_exam_question(question_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    cursor.execute('SELECT * FROM examquestions WHERE id = %s', (question_id,))
    question = cursor.fetchone()

    if request.method == 'POST':
        sql = '''
        UPDATE examquestions
        SET question_text = %s, option_a = %s, option_b = %s, option_c = %s, option_d = %s, correct_answer = %s
        WHERE id = %s
        '''
        cursor.execute(sql, (
            request.form['question_text'],
            request.form.get('option_a'),
            request.form.get('option_b'),
            request.form.get('option_c'),
            request.form.get('option_d'),
            request.form['correct_answer'],
            question_id
        ))

        conn.commit()
        cursor.close()
        conn.close()

        return redirect(url_for('exam_list', paper_id=question['paper_id']))

    cursor.close()
    conn.close()

    return render_template('edit_exam_question.html', question=question)

@app.route('/preview_exam/<int:paper_id>', methods=['GET'])
def preview_exam(paper_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    cursor.execute('SELECT * FROM papers WHERE id = %s', (paper_id,))
    exam = cursor.fetchone()

    cursor.execute('SELECT * FROM examquestions WHERE paper_id = %s', (paper_id,))
    questions = cursor.fetchall()

    cursor.close()
    conn.close()

    return render_template('preview_exam.html', exam=exam, questions=questions)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)
